import { BaseController } from './BaseController.js';
import { ProductModel } from '../model/ProductModel.js';
import ProductDTO from '../dto/ProductDTO.js';

export class ProductController extends BaseController {
    constructor() {
        const productModel = new ProductModel();
        super(productModel);
        this.productModel = productModel;
    }

    // 获取所有产品（分页和筛选）
    async getAllProducts({ page = 1, limit = 10, category, minPrice, maxPrice, search }) {
        try {
            const result = await super.getPaginatedData({
                page,
                limit,
                search,
                filters: { category, minPrice, maxPrice },
                searchFields: ['name', 'description', 'sku']
            });
            
            return {
                products: result.data,
                pagination: result.pagination
            };
        } catch (error) {
            throw new Error(`Failed to get products: ${error.message}`);
        }
    }

    // 根据ID获取产品
    async getProductById(id) {
        try {
            const product = await super.getById(id);
            
            if (product) {
                // 增加查看次数
                await this.productModel.incrementViewCount(id);
            }
            
            return product;
        } catch (error) {
            throw new Error(`Failed to get product: ${error.message}`);
        }
    }

    // 创建新产品
    async createProduct(productData) {
        try {
            // 使用DTO验证产品数据
            const validation = ProductDTO.validateCreate(productData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const validatedData = validation.data;
            
            // 检查产品名称是否已存在
            const existingProduct = await this.productModel.findByName(validatedData.name);
            if (existingProduct) {
                throw new Error('Product name already exists');
            }
            
            // 生成产品SKU（如果没有提供）
            if (!validatedData.sku) {
                validatedData.sku = await this._generateSKU(validatedData.name, validatedData.category);
            }
            
            // 设置默认值
            const productToCreate = {
                ...validatedData,
                status: validatedData.status || 'active',
                stock_quantity: validatedData.stock_quantity || 0,
                view_count: 0
            };
            
            const newProduct = await super.create(productToCreate);
            return newProduct;
        } catch (error) {
            throw new Error(`Failed to create product: ${error.message}`);
        }
    }

    // 更新产品
    async updateProduct(id, updateData) {
        try {
            // 使用DTO验证更新数据
            const validation = ProductDTO.validateUpdate(updateData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const validatedData = validation.data;
            
            // 检查产品名称唯一性（排除当前产品）
            if (validatedData.name) {
                const existingProduct = await this.productModel.findByNameExcludeId(
                    validatedData.name,
                    id
                );
                
                if (existingProduct) {
                    throw new Error('Product name already exists');
                }
            }
            
            const updatedProduct = await super.update(id, validatedData);
            return updatedProduct;
        } catch (error) {
            throw new Error(`Failed to update product: ${error.message}`);
        }
    }

    // 删除产品
    async deleteProduct(id) {
        try {
            return await super.delete(id);
        } catch (error) {
            throw new Error(`Failed to delete product: ${error.message}`);
        }
    }

    // 获取产品分类
    async getCategories() {
        try {
            const categories = await this.productModel.getDistinctCategories();
            return categories;
        } catch (error) {
            throw new Error(`Failed to get categories: ${error.message}`);
        }
    }

    // 批量更新库存
    async batchUpdateInventory(updates) {
        try {
            // 验证更新数据
            if (!Array.isArray(updates) || updates.length === 0) {
                throw new Error('Updates must be a non-empty array');
            }
            
            for (const update of updates) {
                if (!update.id || typeof update.stock !== 'number' || update.stock < 0) {
                    throw new Error('Each update must have valid id and non-negative stock');
                }
            }
            
            const results = [];
            
            for (const update of updates) {
                try {
                    const updatedProduct = await this.productModel.updateStock(update.id, update.stock);
                    results.push({
                        id: update.id,
                        success: true,
                        product: updatedProduct
                    });
                } catch (error) {
                    results.push({
                        id: update.id,
                        success: false,
                        error: error.message
                    });
                }
            }
            
            return {
                total: updates.length,
                successful: results.filter(r => r.success).length,
                failed: results.filter(r => !r.success).length,
                results
            };
        } catch (error) {
            throw new Error(`Failed to batch update inventory: ${error.message}`);
        }
    }

    // 检查库存不足的产品
    async getLowStockProducts(threshold = 10) {
        try {
            const products = await this.productModel.findLowStock(threshold);
            return products;
        } catch (error) {
            throw new Error(`Failed to get low stock products: ${error.message}`);
        }
    }

    // 获取热门产品（按查看次数）
    async getPopularProducts(limit = 10) {
        try {
            const products = await this.productModel.findPopular(limit);
            return products;
        } catch (error) {
            throw new Error(`Failed to get popular products: ${error.message}`);
        }
    }

    // 验证产品数据
    // 更新库存
    async updateStock(id, stockData) {
        try {
            // 使用DTO验证库存更新数据
            const validation = ProductDTO.validateStockUpdate(stockData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const { stock_quantity, operation } = validation.data;
            
            // 获取当前产品信息
            const product = await this.productModel.findById(id);
            if (!product) {
                throw new Error('Product not found');
            }
            
            let newStockQuantity;
            
            switch (operation) {
                case 'add':
                    newStockQuantity = product.stock_quantity + stock_quantity;
                    break;
                case 'subtract':
                    newStockQuantity = Math.max(0, product.stock_quantity - stock_quantity);
                    break;
                case 'set':
                default:
                    newStockQuantity = stock_quantity;
                    break;
            }
            
            const updatedProduct = await super.update(id, { stock_quantity: newStockQuantity });
            return updatedProduct;
        } catch (error) {
            throw new Error(`Failed to update stock: ${error.message}`);
        }
    }
    
    // 更新价格
    async updatePrice(id, priceData) {
        try {
            // 使用DTO验证价格更新数据
            const validation = ProductDTO.validatePriceUpdate(priceData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const validatedData = validation.data;
            
            const updatedProduct = await super.update(id, validatedData);
            return updatedProduct;
        } catch (error) {
            throw new Error(`Failed to update price: ${error.message}`);
        }
    }

    // 生成SKU
    _generateSKU(name, category) {
        const namePrefix = name.substring(0, 3).toUpperCase();
        const categoryPrefix = category ? category.substring(0, 2).toUpperCase() : 'GN';
        const timestamp = Date.now().toString().slice(-6);
        const random = super.generateRandomString(2).toUpperCase();
        
        return `${namePrefix}${categoryPrefix}${timestamp}${random}`;
    }
}